package com.jingdianjichi.wx.handler;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WxChatMsgFactory implements InitializingBean {

    //实现类
    @Resource
    private List<WxChatMsgHandler> wxChatMsgHandlerList;

    //WxChatMsgTypeEnum 枚举的某个对象   WxChatMsgHandler实现类
    private Map<WxChatMsgTypeEnum, WxChatMsgHandler> handlerMap = new HashMap<>();

    /**
     * 通过枚举类型获取到对应的实现类
     * @param msgType
     * @return
     */
    public WxChatMsgHandler getHandlerByMsgType(String msgType){
        //调用枚举类里的静态方法，获取对应的枚举对象
        WxChatMsgTypeEnum msgTypeEnum = WxChatMsgTypeEnum.getByMsgType(msgType);
        return handlerMap.get(msgTypeEnum);
    }


    /**
     * 初始化bean后的操作  将枚举对象K,实现类V存入到HashMap
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (WxChatMsgHandler wxChatMsgHandler : wxChatMsgHandlerList) {
            handlerMap.put(wxChatMsgHandler.getMsgType(),wxChatMsgHandler);
        }
    }
}
